<template>
	<view class="content">
		<uni-fab ref="fab"  horizontal="right" vertical="bottom" />
		<!--
		* 广告组件
		* timedown 倒计时时间
		* imageUrl 背景图
		* url 跳转链接
		*  -->
		<!-- #ifndef MP -->
		<!-- <mix-advert 
			ref="mixAdvert" 
			:timedown="8" 
			imageUrl="/static/advert.jpg"
			:url="advertNavUrl"
		></mix-advert> -->
		<!-- #endif -->

		<!-- 顶部选项卡 -->
		<scroll-view id="nav-bar" class="nav-bar" scroll-x scroll-with-animation :scroll-left="scrollLeft">
			<view v-for="(item,index) in tabBars" :key="item.cid" class="nav-item" :class="{current: index === tabCurrentIndex}"
			 :id="'tab'+index" @click="changeTab(index)">{{item.name}}</view>
		</scroll-view>

		<!-- 下拉刷新组件 -->
		<mix-pulldown-refresh ref="mixPulldownRefresh" class="panel-content" :top="90" @refresh="onPulldownReresh"
		 @setEnableScroll="setEnableScroll">
			<!-- 内容部分 -->
			<swiper id="swiper" class="swiper-box" :duration="300" :current="tabCurrentIndex" @change="changeTab">
				<swiper-item v-for="(tabItem,tabItemIndex) in tabBars" :key="tabItem.cid">
					<scroll-view class="panel-scroll-box " :scroll-y="enableScroll" @scrolltolower="loadMore">
						
						<!-- 轮播图 -->
						<swiper class="screen-swiper round-dot"   :indicator-dots="true" :circular="true"
						 :autoplay="true" interval="5000" duration="500" v-if="tabItem.adPic !== undefined && tabItem.adPic.length >0">
							<swiper-item v-for="(item,adIndex) in tabItem.adPic" :key="adIndex">
								<image :src="item.picUrl" mode="aspectFit"></image>
							</swiper-item>
						</swiper>
						
						<!-- 分类部分 -->
						<view class="cu-list grid col-5 no-border " style="padding-bottom: 0;">
							<view @click="changeCurrentCateId(itemContent.q)" class="cu-item" v-for="(itemContent,indexContent) in tabItem.content" :key="indexContent" v-if="indexContent < 10" style="padding-bottom: 0;">
								<image v-bind:src="itemContent.q_pic" style="height: 80upx;" mode="aspectFit"></image>
								<text>{{itemContent.q}}</text>
							</view>
						</view>
						
						<goodsFilter :filters="goodsFilters" @sortChanged="goodsFilterChanged" @shapeChanged="goodsTemplateChanged" :showShape="true" :shapeValue="2">
						</goodsFilter>

						<!-- 商品列表 -->
						<view class="page" style="background-color: white;">

							<view class="uni-product-list">
								<view @click="navToDetails(product)" class="uni-product" v-for="(product,index2) in tabItem.productList" :key="index2" style="padding-top: 3px;">
									<view class="image-view">
										<image class="uni-product-image" :src="product.image"></image>
									</view>
									<view class="uni-product-title" style="font-size: 24upx;line-height:none;">
										<text style="padding: 4upx 10upx;font-size: 20upx; color: red;font-weight: 700;border-radius: 4upx;">
											<text v-if="product.userType == 1">天猫</text>
											<text v-if="product.userType == 0">淘宝</text>
										</text>
										{{product.title}}
									</view>
									<view class="uni-product-price">
										<text class="uni-product-price-original" style="font-size: 26upx;font-size: 30upx; margin-left: 10upx;">￥{{product.itemfeeFinal}}</text>
										<text class="uni-product-tip" style="padding: 6upx 16upx; ">{{product.itemfeeCoupon}}元券</text>
										<text class="uni-product-price-favour" style="display: block;text-decoration:none;font-size: 22upx;margin-left: 15upx;">已售 {{product.volume}} 件</text>


									</view>
								</view>
							</view>
						</view>
						<!-- 上滑加载更多组件 -->
						<mix-load-more :status="tabItem.loadMoreStatus"></mix-load-more>
					</scroll-view>
				</swiper-item>
			</swiper>
		</mix-pulldown-refresh>

	</view>
</template>

<script>
	// import mixAdvert from '@/components/mix-advert/vue/mix-advert';
	import json from '@/json'
	import mixPulldownRefresh from '@/components/mix-pulldown-refresh/mix-pulldown-refresh';
	import mixLoadMore from '@/components/mix-load-more/mix-load-more';
	import uniFab from '@/components/uni-fab/uni-fab.vue';
	import goodsFilter from '@/components/yb-filter/index.vue';	//排序标签
	let windowWidth = 0,
		scrollTimer = false,
		tabBar;
	export default {
		components: {
			mixPulldownRefresh,
			mixLoadMore,
			uniFab,
			goodsFilter
			// mixAdvert
		},
		data() {
			return {
				tabCurrentIndex: 0, //当前选项卡索引
				scrollLeft: 0, //顶部选项卡左滑距离
				enableScroll: true,
				tabBars: [],
				title: '商品列表',
				gridCol: 5, //每行显示分类数量
				gridBorder: 0,
				beginTabIndex: 1, //开始请求分类的索引值
			}
		},

		async onLoad() {
			// 获取屏幕宽度
			windowWidth = uni.getSystemInfoSync().windowWidth;
			this.loadTabbars();
		},
		onReady() {
			/**
			 * 启动页广告 使用文档（滑稽）
			 * 1. 引入组件并注册 
			 * 		import mixAdvert from '@/components/mix-advert/vue/mix-advert';
			 *      components: {mixAdvert},
					 <!-- #ifndef MP -->
						<mix-advert 
							ref="mixAdvert" 
							:timedown="8" 
							imageUrl="/static/advert.jpg"
							:url="advertNavUrl"
						></mix-advert>
					<!-- #endif -->
			 * 	2. 调用组件的initAdvert()方法进行初始化
			 * 
			 *  初始化的时机应该是在splash关闭时，否则会造成在app端广告显示了数秒后首屏才渲染出来
			 */
			// #ifndef MP
			// this.$refs.mixAdvert.initAdvert();
			// #endif
		},
		methods: {
			/**
			 * 数据处理方法在vue和nvue中通用，可以直接用mixin混合
			 * 这里直接写的
			 * mixin使用方法看index.nuve
			 */
			//获取分类
			loadTabbars() {
				let tabList = json.tabList;
				tabList.forEach(item => {
					item.newsList = [];
					item.loadMoreStatus = 0; //加载更多 0加载前，1加载中，2没有更多了
					item.refreshing = 0;
				})
				this.tabBars = tabList;
				// this.loadNewsList('add');
			},
			//商品列表
			loadNewsList(type) {
				let tabItem = this.tabBars[this.tabCurrentIndex];

				//type add 加载更多 refresh下拉刷新
				if (type === 'add') {
					if (tabItem.loadMoreStatus === 2) {
						return;
					}
					tabItem.loadMoreStatus = 1;
				}
				// #ifdef APP-PLUS
				else if (type === 'refresh') {
					tabItem.refreshing = true;
				}
				// #endif


				if (type === 'refresh') {
					tabItem.productList = []; //刷新前清空数组
				}
				//如果索引值大于配置的分类索引值，则开始求请求数据
				if (this.tabCurrentIndex >= this.beginTabIndex) {
					//如果商品数据不为空，则继续请求
					if (tabItem.catePageEmpty == false) {
						//根据分类请求商品列表
						this.getCateProduct();
					}

				}


				//下拉刷新 关闭刷新动画
				if (type === 'refresh') {
					this.$refs.mixPulldownRefresh && this.$refs.mixPulldownRefresh.endPulldownRefresh();
					// #ifdef APP-PLUS
					tabItem.refreshing = false;
					// #endif
					tabItem.loadMoreStatus = 0;
				}
				
				//上滑加载 处理状态
				if (type === 'add' && tabItem.productList != undefined) {
					tabItem.loadMoreStatus = tabItem.productList.length > 40000 ? 2 : 0;
				}else{
					tabItem.loadMoreStatus = 0;
				}

			},

			//商品详情
			navToDetails(item){
				uni.navigateTo({
					url: `/pages/detail/detail?data=${JSON.stringify(item)}`
				})
			},
			
			//获取商品数据
			getCateProduct() {
				let tabItem = this.tabBars[this.tabCurrentIndex];
				let index = this.tabCurrentIndex;
				let url = '';
				let itemId = '554832820990';
				if(index == 1){
					uni.getStorage({
						key: 'guessItemId',
						success: function (res) {
							itemId = res.data
						}
					});
					//猜你喜欢
					
					url = 'https://api.zhetaoke.com:10001/api/open_item_guess_like.ashx?appkey=7457f07276df46b8b3f1dbd506117ad5&page=' + tabItem.catePage +'&page_size=10&sort=new&item_id='+itemId; //请求分类商品接口。
				}else{
					//分类商品
					url = 'https://api.zhetaoke.com:10001/api/api_all.ashx?appkey=7457f07276df46b8b3f1dbd506117ad5&page=' + tabItem.catePage +'&page_size=10&sort=new&cid=' + tabItem.cid + '&q=' + tabItem.currentQ; //请求分类商品接口。
				}
				
				uni.request({
					url: url, //请求分类商品接口。
				
					success: (res) => {
						tabItem.catePage++;

						if (res.statusCode == 200) {

							if (res.data.content.length >= 0) {
								//商品数据数量大于0，则压入数组
								res.data.content.forEach(item => {
									 
									//推送商品
									tabItem.productList.push({
										'image': item.pict_url + '_300x300', //封面图
										'title': item.title,				//标题
										'itemfee': item.size,				//原价
										'itemfeeFinal': item.quanhou_jiage,	//券后价
										'volume': item.volume,				//销量
										'userType': item.user_type,			//是否天猫，0是淘宝，1是天猫
										'itemId':item.tao_id,				//商品ID
										'jianjie':item.jianjie,				//商品简介
										
										'score1':item.score1,				//宝贝描述分
										'score2':item.score2,				//卖家服务分
										'score3':item.score3,				//物流服务分
										'shopIcon':item.shopIcon,			//店铺logo
										'shopTitle':item.shop_title,		//店铺名称
										'nick':item.nick,					//卖家昵称
										'provcity':item.provcity,			//宝贝所在地
										
										'content':item.pcDescContent,		//图文详情图片地址
										'smallImages':item.small_images,	//商品小图列表
										'video':item.zhibo_url,				//视频地址
										
										'couponStartTime':item.coupon_start_time,	//优惠劵开始时间
										'couponEndTime':item.coupon_end_time,	//优惠劵结束时间
										'itemfeeCoupon': parseInt(item.coupon_info_money),
									});
								});
							}


							//下一页商品数据为空
							if (res.data.content.length < 10 && index !=1) tabItem.catePageEmpty = true;
						} else {

							uni.showToast({
								title: '网络错误'
							});
						}

						this.text = 'request success';
					}
				});

			},

			//获取子分类商品数据
			changeCurrentCateId($q) {

				let tabItem = this.tabBars[this.tabCurrentIndex];
				tabItem.productList = [];
				tabItem.currentQ = $q;
				tabItem.catePageEmpty = false;
				tabItem.catePage = 1;
				this.loadNewsList('add');
			},

			//下拉刷新
			onPulldownReresh() {
				this.loadNewsList('refresh');
			},

			//上滑加载
			loadMore() {
				this.loadNewsList('add');
			},

			//设置scroll-view是否允许滚动，在小程序里下拉刷新时避免列表可以滑动
			setEnableScroll(enable) {
				if (this.enableScroll !== enable) {
					this.enableScroll = enable;
				}
			},

			//tab切换
			async changeTab(e) {

				if (scrollTimer) {
					//多次切换只执行最后一次
					clearTimeout(scrollTimer);
					scrollTimer = false;
				}
				let index = e;
				//e=number为点击切换，e=object为swiper滑动切换
				if (typeof e === 'object') {
					index = e.detail.current
				}
				if (typeof tabBar !== 'object') {
					tabBar = await this.getElSize("nav-bar")
				}
				//计算宽度相关
				let tabBarScrollLeft = tabBar.scrollLeft;
				let width = 0;
				let nowWidth = 0;
				//获取可滑动总宽度
				for (let i = 0; i <= index; i++) {
					let result = await this.getElSize('tab' + i);
					width += result.width;
					if (i === index) {
						nowWidth = result.width;
					}
				}
				if (typeof e === 'number') {
					//点击切换时先切换再滚动tabbar，避免同时切换视觉错位
					this.tabCurrentIndex = index;
				}
				//延迟300ms,等待swiper动画结束再修改tabbar
				scrollTimer = setTimeout(() => {
					if (width - nowWidth / 2 > windowWidth / 2) {
						//如果当前项越过中心点，将其放在屏幕中心
						this.scrollLeft = width - nowWidth / 2 - windowWidth / 2;
					} else {
						this.scrollLeft = 0;
					}
					if (typeof e === 'object') {
						this.tabCurrentIndex = index;
					}
					this.tabCurrentIndex = index;


					//第一次切换tab，动画结束后需要加载数据
					let tabItem = this.tabBars[this.tabCurrentIndex];
					if (this.tabCurrentIndex !== 0 && tabItem.loaded !== true) {
						this.loadNewsList('add');
						tabItem.loaded = true;
					}
				}, 300)

			},
			//获得元素的size
			getElSize(id) {
				return new Promise((res, rej) => {
					let el = uni.createSelectorQuery().select('#' + id);
					el.fields({
						size: true,
						scrollOffset: true,
						rect: true
					}, (data) => {
						res(data);
					}).exec();
				});
			},
			
		}
	}
</script>

<style lang='scss'>
	@import '../../common/uni.css';
	@import '../../graceUI/graceUI.css'; 
	page,
	.content {
		background-color: #f8f8f8;
		height: 100%;
		overflow: hidden;
	}

	/* 顶部tabbar */
	.nav-bar {
		position: relative;
		z-index: 10;
		height: 90upx;
		white-space: nowrap;
		box-shadow: 0 2upx 8upx rgba(0, 0, 0, .06);
		background-color: #fff;

		.nav-item {
			display: inline-block;
			width: 150upx;
			height: 90upx;
			text-align: center;
			line-height: 90upx;
			font-size: 30upx;
			color: #303133;
			position: relative;

			&:after {
				content: '';
				width: 0;
				height: 0;
				border-bottom: 4upx solid #007aff;
				position: absolute;
				left: 50%;
				bottom: 0;
				transform: translateX(-50%);
				transition: .3s;
			}
		}

		.current {
			color: #007aff;

			&:after {
				width: 50%;
			}
		}
	}

	.swiper-box {
		height: 100%;
	}

	.panel-scroll-box {
		height: 100%;

		.panel-item {
			background: #fff;
			padding: 30px 0;
			border-bottom: 2px solid #000;
		}
	}

	/**
	 * 新闻列表 直接拿的nvue样式修改，,
	 * 一共需要修改不到10行代码, 另外px需要直接修改为upx，只有单位不一样，计算都是一样的
	 * 吐槽：难道不能在编译的时候把nuve中的upx转为px? 这样就不用修改单位了
	 */
	.video-wrapper {
		width: 100%;
		height: 440upx;

		.video {
			width: 100%;
		}
	}

	.img {
		width: 100%;
		height: 100%;
	}

	.news-item {
		position: relative;
	}

	/* 修改结束 */

	/* 新闻列表  emmm 仅供参考 */
	.news-item {
		width: 750upx;
		padding: 24upx 30upx;
		border-bottom-width: 1px;
		border-color: #eee;
		background-color: #fff;
	}

	.title {
		font-size: 32upx;
		color: #303133;
		line-height: 46upx;
	}

	.bot {
		flex-direction: row;
	}

	.author {
		font-size: 26upx;
		color: #aaa;
	}

	.time {
		font-size: 26upx;
		color: #aaa;
		margin-left: 20upx;
	}

	.img-list {
		flex-shrink: 0;
		flex-direction: row;
		background-color: #fff;
		width: 220upx;
		height: 140upx;
	}

	.img-wrapper {
		flex: 1;
		flex-direction: row;
		height: 140upx;
		position: relative;
		overflow: hidden;
	}

	.img {
		flex: 1;
	}

	.img-empty {
		height: 20upx;
	}

	/* 图在左 */
	.img-list1 {
		position: absolute;
		left: 30upx;
		top: 24upx;
	}

	.title1 {
		padding-left: 240upx;
	}

	.bot1 {
		padding-left: 240upx;
		margin-top: 20upx;
	}

	/* 图在右 */
	.img-list2 {
		position: absolute;
		right: 30upx;
		top: 24upx;
	}

	.title2 {
		padding-right: 210upx;
	}

	.bot2 {
		margin-top: 20upx;
	}

	/* 底部3图 */
	.img-list3 {
		width: 700upx;
		margin: 16upx 0upx;
	}

	.img-wrapper3 {
		margin-right: 4upx;
	}

	/* 底部大图 */
	.img-list-single {
		width: 690upx;
		height: 240upx;
		margin: 16upx 0upx;
	}

	.img-wrapper-single {
		height: 240upx;
		margin-right: 0upx;
	}

	.video-tip {
		position: absolute;
		left: 0;
		top: 0;
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, .3);
	}

	.video-tip-icon {
		width: 60upx;
		height: 60upx;
	}
</style>
